package cn.wolfcode.luowowo.member.service.impl;


import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.common.util.AssertUtil;
import cn.wolfcode.luowowo.common.util.CheckMobile;
import cn.wolfcode.luowowo.common.util.Consts;
import cn.wolfcode.luowowo.common.util.LogicException;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.mapper.UserInfoMapper;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    //根据id查找用户
    public UserInfo get(Long id) {
        return userInfoMapper.selectByPrimaryKey(id);
    }

    //根据电话号码,查找用户是否存在
    public boolean checkPhone(String phone) {
        return userInfoMapper.selectCountByPhone(phone) > 0 ;
    }

    //生成验证码,并存入redis中
    public void sendVerifyCode(String phone) throws LogicException {
        AssertUtil.hasLength(phone,"手机号不能为空");
        //判断用户是否频繁发送信息
        String hasPhone = userInfoRedisService.getPhone(phone);
        if (hasPhone == null) {
            userInfoRedisService.setPhone(phone);
            String verifyCode = userInfoRedisService.getVerifyCode(phone);
            if (verifyCode == null) {
                verifyCode = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 4);

                //模拟发送短信信息
                StringBuilder stringBuilder = new StringBuilder(100);
                stringBuilder.append("你的验证码是:").append(verifyCode)
                        .append(" 请在" + Consts.VERIFY_CODE_VAI_TIME + "分钟内完成注册");
                System.out.println(stringBuilder);

                //将验证码存入reids中
                userInfoRedisService.setVerifyCode(phone, verifyCode);
            } else {
                //模拟发送短信信息
                StringBuilder stringBuilder = new StringBuilder(100);
                stringBuilder.append("你的验证码是:").append(verifyCode)
                        .append(" 请在" + Consts.VERIFY_CODE_VAI_TIME + "分钟内完成注册");
                System.out.println(stringBuilder);

                //将验证码存入reids中
                userInfoRedisService.setVerifyCode(phone, verifyCode);
            }
        } else {
            throw new LogicException("操作过于频繁,请稍后再试");
        }

    }

    //用户注册
    public void userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) throws LogicException {
        //判断传过来的参数是否为空
        AssertUtil.hasLength(phone, "电话号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");

        //判断用户两次密码是否一致
        if (!password.equals(rpassword)) {
            throw new LogicException("两次密码不一致");
        }

        //手机号码格式是否正确
        if (!CheckMobile.isMobile(phone)) {
            throw new LogicException("手机号码格式不正确");
        }

        //验证验证码是否正确
        String code =  userInfoRedisService.getVerifyCode(phone);
        AssertUtil.equale(code, verifyCode, "验证码错误或已超时");

        //在数据库中存入用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setLevel(1);   //设置用户等级
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setPassword(password);
        userInfo.setState(UserInfo.STATE_NORMAL);   //设置用户状态为正常
        userInfoMapper.insert(userInfo);

    }

    //用户登录
    public String userLogin(String username, String password) throws LogicException {
        //判断用户账号密码是否为空
        AssertUtil.hasLength(username,"账号不能为空");
        AssertUtil.hasLength(password,"密码不能为空");
        //判断用户是否存在
        UserInfo user = userInfoMapper.selectByUsernameAndPassword(username, password);
        if (user == null) {
            throw new LogicException("账号或密码不对");
        }

        //创建token
        String token = UUID.randomUUID().toString().replaceAll("-","");
        userInfoRedisService.setTokenByUser(token,user);

        //我们在可以在这边利一token为cookie的值传给服务器,但是这样项目结构不严谨,cookie共享是表现层的事,而这边是业务层
        return token;
    }

    //查询所有用户
    public List<UserInfo> list() {
        return userInfoMapper.selectAll();
    }
//修改用户的基本信息
    public void setting(UserInfo user) {
        userInfoMapper.updateBydata(user);
    }

    public void uploadHeadImgUrl(String photo, Long id) {

        userInfoMapper.updateHeadImgUrl(photo,id);
    }

    public void setPassword(Long id, String password, String rpassword, String verifyCode) {
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "新密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(id);
        if (!userInfo.getPassword().equals(password)){
            throw new LogicException("旧密码不对");
        }
        //验证验证码是否正确
        UserInfo user = userInfoMapper.selectByPrimaryKey(id);
        String code =  userInfoRedisService.getVerifyCode(user.getPhone());
        AssertUtil.equale(code, verifyCode, "验证码错误或已超时");
        //在数据库中存入用户信息
        user.setPassword(rpassword);
        userInfoMapper.updatePassword(user);
    }


    public int selectGoldnumById(Long id) {
        return userInfoMapper.selectGoldnumById(id);
    }
    public void checkCode(String code, String phone) throws LogicException{
        AssertUtil.hasLength(code, "验证码不能为空");
        //验证验证码是否正确
        String mycode =  userInfoRedisService.getVerifyCode(phone);
        AssertUtil.equale(mycode, code, "验证码错误或已超时");
        //在数据库中存入用户信息
    }

    public void setPhone(String code, String phone,Long uid)  throws LogicException{
        this.checkCode(code,phone);
        userInfoMapper.updatePhone(phone, uid);
    }

    @Override
    public UserInfo getScoreById(Long userId) {
        return userInfoMapper.getScoreById(userId);
    }

    @Override
    public void updateScore(Long userId, Long price) {
        userInfoMapper.updateScore(userId,price);
    }

    @Override
    public void updateBuy(Long userId, Long shopId) {
        UserInfo userInfo = userInfoMapper.getScoreById(userId);
        String sd = userInfo.getShopId(); //商品字符串

        if(sd != null){
            List<String> list = new ArrayList<>();

            String[] split = sd.split(",");

            for (int i = 0; i < split.length; i++) {
                list.add(split[i]);
            }

            list.add(String.valueOf(shopId));

            String str = "";
            for (int i = 0; i < list.size(); i++) {
                if(i < list.size()-1){
                    str += list.get(i) + ",";
                }else{
                    str += list.get(i);
                }
            }
            userInfo.setShopId(str);
        }else{
            userInfo.setShopId(String.valueOf(shopId));
        }

        userInfoMapper.updateBuy(userInfo);
    }

}
